package cn.com.xiaoshoujia.activities.controller;

import cn.com.xiaoshoujia.quartz.wx.TeamHeadQuartz;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author: yangrui
 * @Description: 定时器测试，待删除
 * @Date: 下午5:39 2017/8/3
 */
//@RestController
public class QuartzTestController {

    @Resource(name = "schedulerFactoryBean")
    private Scheduler scheduler;

    public static String dateFormate = "ss mm HH dd MM ? yyyy";
    public static SimpleDateFormat cronSdf = new SimpleDateFormat(dateFormate);

    /**
     * @Author: yangrui
     * @Description: 动态定时器
     * @Date: 下午7:07 2017/8/3
     */
    @GetMapping(value = "quartz")
    public String quartz() {
        String time = String.valueOf(System.currentTimeMillis());
        String jobName = "job" + time;
        String triggerName = "trigger" + time;
        JobKey jobKey = JobKey.jobKey(jobName, "group");
        JobDetail job = JobBuilder.newJob(TeamHeadQuartz.class).withIdentity(jobKey).build();

        Calendar rightNow = Calendar.getInstance();
        Date date = new Date();
        rightNow.setTime(date);
        rightNow.add(Calendar.SECOND, 30);//日期加10秒

        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, "group")
                .withSchedule(CronScheduleBuilder.cronSchedule(cronSdf.format(rightNow.getTime())))
                .build();

        try {
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
//            try {
//                Thread.sleep(5000);
//
//                scheduler.deleteJob(jobKey);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return "1";
    }
}
